import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, cross_validate
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn import preprocessing
from sklearn.model_selection import GridSearchCV

from sklearn.svm import OneClassSVM

import joblib

def train(dataPath, modelSavePath):
    print('\ntraining: ', dataPath)

    # Importing the dataset
    dataset_normal = pd.read_csv('../../data/ingotRate_normal.csv')
    X_normal = dataset_normal.iloc[:, :-1]
    X_normal_scaled = preprocessing.StandardScaler().fit_transform(X_normal)
    y_normal = dataset_normal.iloc[:, dataset_normal.shape[1] - 1]

    dataset_abnormal = pd.read_csv('../../data/ingotRate_abnormal.csv')
    X_abnormal = dataset_abnormal.iloc[:, :-1]
    X_abnormal_scaled = preprocessing.StandardScaler().fit_transform(X_abnormal)
    y_abnormal = dataset_abnormal.iloc[:, dataset_abnormal.shape[1] - 1]

    dataset = pd.read_csv(dataPath)
    X = dataset.iloc[:, :-1]
    y = dataset.iloc[:, dataset.shape[1] - 1]

    # normalize
    X_scaled = preprocessing.StandardScaler().fit_transform(X)
    # X_scaled = preprocessing.MinMaxScaler().fit_transform(X)
    # X_scaled = preprocessing.MaxAbsScaler().fit_transform(X)
    # X_scaled = preprocessing.Normalizer().fit_transform(X)

    # X_scaled = preprocessing.Normalizer().fit_transform(X)

    # total_score=0
    # for ti in range(0,20):
    #     print('==============round: ',ti,'====================')
    # Splitting the dataset into the Training set and Test set
    # X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=0)
    if dataPath == '../../data/ingotRate.csv':
        X_train, X_test, y_train, y_test = train_test_split(X_scaled, y.values, test_size=0.2, random_state=3)
    elif dataPath == '../../data/yieldRate.csv':
        X_train, X_test, y_train, y_test = train_test_split(X_scaled, y.values, test_size=0.2, random_state=0)


    print('\nnormal train: ')
    model_normal=OneClassSVM(kernel='linear', nu=0.001, gamma='scale', degree=10)
    model_normal.fit(X_normal_scaled)
    pred=model_normal.predict(X_normal_scaled)
    print(pred)
    scores=model_normal.score_samples(X_normal_scaled)
    print(scores)

    print('\nnormal test: ')
    pred=model_normal.predict(X_abnormal_scaled)
    print(pred)
    scores=model_normal.score_samples(X_abnormal_scaled)
    print(scores)


    # print('\nabnormal train: ')
    # model_abnormal=OneClassSVM(kernel='linear', nu=0.0001)
    # model_abnormal.fit(X_abnormal)
    # pred=model_abnormal.predict(X_abnormal)
    # print(pred)
    # scores=model_abnormal.score_samples(X_abnormal)
    # print(scores)
    #
    # print('\nabnormal test: ')
    # pred=model_abnormal.predict(X)
    # print(pred)
    # scores=model_abnormal.score_samples(X)
    # print(scores)


def predict(predictionObject, data):
    regressor = None
    testData = None
    if predictionObject == 'ingotRate':
        regressor = joblib.load('./ingotRatePrediction.pkl')
        testData = pd.DataFrame(data,
                                columns=['WS_MM', 'CS_MM', 'FS_MM', 'Mn_MM', 'CL_SM', 'Out_TE', 'S_EL', 'SN_QM',
                                         'UD_QM', 'NI_QM', 'OE_QM', 'PO_QM', 'C_QM', 'SI_QM'], dtype=float)
    elif predictionObject == 'yieldRate':
        regressor = joblib.load('./yieldRatePrediction.pkl')
        testData = pd.DataFrame(data,
                                columns=['X31', 'X33', 'X34', 'X35', 'X36'], dtype=float)

    testData = preprocessing.scale(testData)
    result = regressor.predict(testData)
    print('result:\n', result[0])
    return result[0]

if __name__ == '__main__':
    train('../../data/ingotRate.csv', './ingotRatePrediction.pkl')
    # train('../../data/yieldRate.csv','./yieldRatePrediction.pkl')

    # data = [[3.12, 6.12, 8.61, 5.82, 2.44, 1.59, 1.24, 0.66, 0.143, 1.824, 1.126, 1.46, 0.38, 0.46]]  # ingotRate
    # predict('ingotRate', data)
    # data = [[6.684, 2.561, 1.654, 1.36, 0.679]]  # yieldRate
    # predict('yieldRate', data)